package com.zcaxer.roomwordsample.workers

import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.zcaxer.roomwordsample.data.AppRoomDatabase
import com.zcaxer.roomwordsample.data.Building
import com.zcaxer.roomwordsample.data.BuildingUpgradeInfo
import kotlinx.coroutines.coroutineScope


class SeedDatabaseWorker(
    context: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {

    private val TAG by lazy { SeedDatabaseWorker::class.java.simpleName }

    override suspend fun doWork(): Result = coroutineScope {
        try {
            applicationContext.assets.open("building.json").use { inputStream ->
                JsonReader(inputStream.reader()).use { jsonReader ->
                    val type = object : TypeToken<List<Building>>() {}.type
                    val buildings: List<Building> =
                        GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(jsonReader, type)
                    val database = AppRoomDatabase.getDatabase(applicationContext)
                    buildings.forEach {

                        database.buildingDao().insert(it.initBuilding())
                        for (item in it.upgradeInfo) {
                            database.buildingUpgradeInfoDao()
                                .insert(
                                    BuildingUpgradeInfo(
                                        it.buildingID,
                                        item.getOrElse("type",{-1}),
                                        item.getOrElse("endLevel", { -1 }),
                                        item.getOrElse("a", { 0 }),
                                        item.getOrElse("b", { 0 }),
                                        item.getOrElse("c", { 0 })
                                    )
                                )
                        }
                    }
                    Result.success()
                }

            }
        } catch (e: Exception) {
            Log.e(TAG, "Error SeedDatabaseWorker")
            println(e.cause)
            println(e.stackTrace)
            Result.failure()
        }
    }


}


